package cz.fi.muni.pb138.spring2013.dtd2xsd;

import cz.fi.muni.pb138.spring2013.dtd2xsd.entities.Document;
import cz.fi.muni.pb138.spring2013.dtd2xsd.parse.Parser;
import cz.fi.muni.pb138.spring2013.dtd2xsd.visitor.implementation.XMLSchemaVisitor;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

/**
 * This class represents the whole application.
 * It is responsible for checking all errors and giving response to the user
 * @author Slavomir Krupa
 */
public class App {

    private static final String XMLSchemaHeader = " xs:noNamespaceSchemaLocation=\"schema.xsd\" xmlns=\"\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\" ";

    /**
     * Main method. Requires two parameters.
     * @param args args[0]: path to input file, args[1]: output file name
     */
    public static void main(String[] args) {
        if (args.length == 2) {
            BufferedWriter xmlOut = null;
            OutputStream schemaOut = null;
            try {
                Parser parser = new Parser();
                XMLSchemaVisitor visitor = new XMLSchemaVisitor();
                String pathToInput = args[0];
                if (args[0].lastIndexOf('/') + 1 == -1) {
                    System.err.println("Filepath is wrong !");
                    return;
                }
                String relativePath = args[0].substring(0, args[0].lastIndexOf('/') + 1);
                String pathToOutput = relativePath + args[1];
                String pathToSchema = relativePath + "schema.xsd";
                System.out.println("Parsing DTD");
                Document document = parser.parse(pathToInput);
                if(document == null) {
                    System.err.println("Something went wrong in process of parsing. Please check documentation for more hints.");
                    return;
                }
                System.out.println("DTD sucessfully parsed!");
                System.out.println("Creating output files");
                xmlOut = new BufferedWriter(new PrintWriter(new FileOutputStream(pathToOutput)));
                schemaOut = new FileOutputStream(pathToSchema);
                System.out.println("Output files created");
                System.out.println("Building XMLSchema from in-memory format");
                document.accept(visitor);
                System.out.println("XMLSchema built");
                System.out.println("Writing data to output");
                visitor.getPrintableVersion(schemaOut);
                {
                    String rootNodeName = document.getRoot().getName();
                    xmlOut.write(document.getXMLContent().replaceAll("<" + rootNodeName, "<" + rootNodeName + XMLSchemaHeader));

                }
                System.out.println("DONE!");

            } catch (ParserConfigurationException | TransformerException ex) {
               System.err.println( "Something went terribly wrong - probably problem with JVM");
            } catch (FileNotFoundException ex) {
                System.err.println("Wrong path to the file!");
            } catch (IOException ex) {
                System.err.println( "Error  during IO operation!");
            } finally {
                if (xmlOut != null) {
                    try {
                        xmlOut.close();
                    } catch (IOException ex) {
                        System.err.println( "Error during closing xml output file");
                    }
                    if (schemaOut != null) {
                        try {
                            schemaOut.close();
                        } catch (IOException ex) {
                            System.err.println("Error during closing schema output file");
                        }
                    }
                }
            }

        } else {
            System.err.println("Usage:\"java -jar DTD2XSD.jar  <1> <2>\" \n <1> = path to the XML Document with DTD \n <2> = name of the new XML Document to be created with XMLSchema instead of DTD");
        }

    }
}
